# /**
# * Copyright (c) 2022 Beijing Jiaotong University
# * PhotLab is licensed under [Open Source License].
# * You can use this software according to the terms and conditions of the [Open Source License].
# *
# * You may obtain a copy of [Open Source License] at: [https://open.source.license/]
# *
# * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# *
# * See the [Open Source License] for more details.
# */
# /**
# * Author: Shihao Xie
# * Created: Apr. 19, 2023
# * Supported by: National Key Research and Development Program of China
# */
import os.path

from phot_server.core.exception import ResourceNotFoundError, IdDuplicationException
from phot_server.rpc.project_data_type.ttypes import ProjectConfig
from phot_server.utils.singleton import singleton


# temporarily storage project server_config
@singleton
class ProjectConfigRepository:

    def __init__(self):
        self.__configurations = {}

    def has_project_config(self, project_id):
        return True if self.__configurations.get(project_id, None) is not None else False

    def add_project_config(self, project_config: ProjectConfig):
        if self.has_project_config(project_config.projectId):
            raise IdDuplicationException(ProjectConfig.__name__, project_config.projectId)
        self.__configurations[project_config.projectId] = project_config

    def get_project_config(self, project_id):
        if self.has_project_config(project_id):
            return self.__configurations[project_id]
        else:
            raise ResourceNotFoundError(ProjectConfig.__name__, project_id)

    def get_project_config_by_name(self, main_file_name):
        for project_config in self.__configurations.values():
            if project_config.mainFileName == main_file_name:
                return project_config
        return None

    def delete_project_config(self, project_id):
        if self.has_project_config(project_id):
            return self.__configurations.pop(project_id)
        else:
            raise ResourceNotFoundError(ProjectConfig.__name__, project_id)

    def update_project_config(self, project_id, project_config: ProjectConfig):
        self.delete_project_config(project_id)
        self.add_project_config(project_config)

